package oakclub.model;

import oakclub.jooq.Tables;
import oakclub.jooq.tables.AdminQueue;
import oakclub.jooq.tables.AdminQueueItem;
import org.jooq.DSLContext;
import org.jooq.impl.DSL;

import java.sql.Timestamp;

public class AdminQueueModel extends BaseModel
{
    public void addItem(long userId, int statusId, Long sourceId, String note) throws Exception
    {
        this.execute(new IExecute()
        {
            @Override
            public void execute(DSLContext context, Object... params) throws Exception
            {
                // params
                long userId = (long) params[0];
                int statusId = (int) params[1];
                Long sourceId = (Long) params[2];
                String note = (String) params[3];

                // table alias
                AdminQueue AQ = Tables.ADMIN_QUEUE;
                AdminQueueItem AQI = Tables.ADMIN_QUEUE_ITEM;

                // select queue
                int queueId = context
                    .select(AQ.ID)
                    .from(AQ)
                    .orderBy(DSL.rand())
                    .limit(1)
                    .fetchOne(0, int.class);

                // add item
                Timestamp now = new Timestamp(System.currentTimeMillis());
                context
                    .insertInto(AQI, AQI.USER_ID, AQI.QUEUE_ID, AQI.STATUS_ID, AQI.CREATED_AT, AQI.UPDATED_AT, AQI.SOURCE_ID, AQI.NOTE)
                    .values(userId, queueId, statusId, now, now, sourceId, note)
                    .execute();
            }
        }, userId, statusId, sourceId, note);
    }
}
